package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserServise;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiseImpl implements UserServise {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 获取用户授权码
        String code = userLoginDTO.getCode();
        // 调用微信接口服务，获取openid
        String url = "https://api.weixin.qq.com/sns/jscode2session" ;
        //请求参数
        Map<String,String> paramMap = new HashMap<>();
        //四个参数填充
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        //调用微信接口服务 获取Json数据
        String json = HttpClientUtil.doGet(url, paramMap);
        //将json字符串转换为json对象
        JSONObject jsonObject = JSON.parseObject(json);

        // 获取openid 并判断是否为空
        String openid = jsonObject.getString("openid");
        if(openid == null){
            //
            throw  new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        User user = userMapper.vxLogin(openid);
        if (user == null){
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }


        return user;
    }
}
